package com.fuhao.config.swagger;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @author zhang
 * @title: swaggerConfig
 */
@Component
@Primary
public class swaggerConfig implements SwaggerResourcesProvider {

    @ApolloConfig
    private Config config;

    @Override
    public List<SwaggerResource> get() {
        //写死
        //List resources = new ArrayList<>();
        //resources.add(swaggerResource("fuhao-member-service", "/fuhao-member-service/v2/api-docs", "1.0"));
        //resources.add(swaggerResource("fuhao-weixin-service", "/fuhao-weixin-service/v2/api-docs", "1.0"));
       //阿波罗拉去
        return resources();
    }

    /**
     * 从阿波罗服务器中获取resources
     *
     * @return
     */
    private List<SwaggerResource> resources() {

        List resources = new ArrayList<>();
        // app-itmayiedu-order
        // 网关使用服务别名获取远程服务的SwaggerApi
        String swaggerDocJson = swaggerDocument();
        JSONArray jsonArray = JSONArray.parseArray(swaggerDocJson);
        for (Object object : jsonArray) {
            JSONObject jsonObject = (JSONObject) object;
            String name = jsonObject.getString("name");
            String location = jsonObject.getString("location");
            String version = jsonObject.getString("version");
            resources.add(swaggerResource(name, location, version));
        }
        return resources;
    }

    /**
     * 获取swaggerDocument配置
     *
     * @return
     */
    private String swaggerDocument() {
        String property = config.getProperty("zuul.swaggerDocument", "");
        return property;
    }

    private SwaggerResource swaggerResource(String name, String location, String version) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion(version);
        return swaggerResource;
    }

}
